/*******************************************************************************
 * Copyright (c) 2011 Olexandr V. Shaposhnikov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Olexandr V. Shaposhnikov - initial API and implementation and/or initial documentation
 *******************************************************************************/
package com.funkyroach.use.core.parser.antlr;

import org.antlr.runtime.Token;
import org.eclipse.dltk.core.ISourceRange;
import org.eclipse.dltk.core.builder.ISourceLineTracker;

import com.funkyroach.use.core.parser.USSourceRange;

public class USLineTracker {
    private final ISourceLineTracker lineTracker;

    public USLineTracker(ISourceLineTracker lineTracker) {
        this.lineTracker = lineTracker;
    }

    public int getOffset(int line, int column) {
        return line >= 1 ? lineTracker.getLineOffset(line - 1) + Math.max(column, 0) : 0;
    }

    public int getLineNumberOfOffset(int offset) {
        return lineTracker.getLineNumberOfOffset(offset);
    }

    public int getLength() {
        return lineTracker.getLength();
    }

    public int getOffset(Token token) {
        if (token == null) {
            throw new IllegalArgumentException();
        }
        return getOffset(token.getLine(), token.getCharPositionInLine());
    }

    public int length(Token token) {
        final String sm = token.getText();
        return sm != null ? sm.length() : 1;
    }

    public ISourceRange toSourceRange(Token token) {
        return new USSourceRange(getOffset(token), length(token));
    }

}
